<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="学生姓名">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入学生姓名"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="listQuery.class" placeholder="请选择班级" clearable>
            <el-option label="初二(1)班" value="初二(1)班" />
            <el-option label="初二(2)班" value="初二(2)班" />
            <el-option label="初二(3)班" value="初二(3)班" />
            <el-option label="初二(4)班" value="初二(4)班" />
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="listQuery.subject" placeholder="请选择学科" clearable>
            <el-option label="语文" value="语文" />
            <el-option label="数学" value="数学" />
          </el-select>
        </el-form-item>
        <el-form-item label="聚类类型">
          <el-select v-model="listQuery.clusterType" placeholder="请选择聚类类型" clearable>
            <el-option label="优秀进取型" value="优秀进取型" />
            <el-option label="稳定发展型" value="稳定发展型" />
            <el-option label="潜力待发型" value="潜力待发型" />
            <el-option label="困难提升型" value="困难提升型" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="exportData">导出数据</el-button>
          <el-button type="warning" @click="generateRecommendations">生成学习推荐</el-button>
          <el-button type="danger" @click="cleanData">清除异常数据</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
    >
      <el-table-column prop="name" label="学生姓名" />
      <el-table-column prop="class" label="班级" width="80" />
      <el-table-column prop="subject" label="学科" width="80" />
      <el-table-column prop="examScore" label="考试成绩" width="80" />
      <el-table-column prop="clusterType" label="聚类类型" width="120">
        <template slot-scope="{row}">
          <el-tag :type="getClusterTagType(row.clusterType)">
            {{ row.clusterType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="weeklyStudyHours" label="每周学习总时长" width="120">
        <template slot-scope="{row}">
          {{ row.weeklyStudyHours }} 小时
        </template>
      </el-table-column>
      <el-table-column prop="homeworkAccuracy" label="作业准确率" width="100">
        <template slot-scope="{row}">
          {{ row.homeworkAccuracy }}%
        </template>
      </el-table-column>
      <el-table-column prop="videoWatchCount" label="视频观看次数" width="120" />
      <el-table-column prop="interactionCount" label="互动次数" width="100" />
      <el-table-column label="操作" width="300">
        <template slot-scope="{row}">
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="handleRowClick(row)">详情</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showStudentProfile(row)">人物画像</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showLearningPath(row)">学习路径</span>
          <span style="color: #409EFF; cursor: pointer;margin-right: 10px;" @click="showRecommendations(row)">学习推荐</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详细信息弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="学生详细信息">
      <div>
        <p>姓名: {{ selectedStudent.name }}</p>
        <p>班级: {{ selectedStudent.class }}</p>
        <p>学科: {{ selectedStudent.subject }}</p>
        <p>考试成绩: {{ selectedStudent.examScore }}</p>
        <p>聚类类型: {{ selectedStudent.clusterType }}</p>
        <p>每周学习总时长: {{ selectedStudent.weeklyStudyHours ? selectedStudent.weeklyStudyHours.reduce((sum, hours) => sum + hours, 0) : 0 }} 小时</p>
        <p>作业准确率: {{ selectedStudent.homeworkAccuracy }}%</p>
        <p>视频观看次数: {{ selectedStudent.videoWatchCount }}</p>
        <p>互动次数: {{ selectedStudent.interactionCount }}</p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 人物画像弹窗 -->
    <el-dialog :visible.sync="portraitDialogVisible" title="人物画像">
      <div>
        <div id="learning-style-radar" style="width: 600px; height: 400px;"></div>
      </div>
      <template #footer>
        <el-button @click="portraitDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 学习路径弹窗 -->
    <el-dialog :visible.sync="pathDialogVisible" title="个性化学习路径">
      <div>
        <div id="learning-path-chart" style="width: 600px; height: 400px;"></div>
      </div>
      <template #footer>
        <el-button @click="pathDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 学习推荐弹窗 -->
    <el-dialog :visible.sync="recommendationDialogVisible" title="个性化学习推荐">
      <div class="recommendation-container">
        <el-card class="recommendation-card">
          <div slot="header">
            <span>学习建议</span>
          </div>
          <div v-for="(item, index) in selectedRecommendations" :key="index" class="recommendation-item">
            <h4>{{ item.title }}</h4>
            <p>{{ item.content }}</p>
          </div>
        </el-card>
      </div>
      <template #footer>
        <el-button @click="recommendationDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import mockData from './mockData.js'
import * as echarts from 'echarts'

export default {
  name: 'ClusterAnalysis',
  components: { Pagination },
  data() {
    return {
      mockData,
      cleanedData: [],
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: undefined,
        clusterType: undefined
      },
      dialogVisible: false,
      selectedStudent: {},
      portraitDialogVisible: false,
      pathDialogVisible: false,
      recommendationDialogVisible: false,
      selectedRecommendations: [],
      isDataCleaned: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getClusterTagType(clusterType) {
      const typeMap = {
        优秀进取型: 'success',
        稳定发展型: 'warning',
        潜力待发型: 'info',
        困难提升型: 'danger'
      }
      return typeMap[clusterType] || 'info'
    },
    getList() {
      this.listLoading = true
      setTimeout(() => {
        let result = this.isDataCleaned ? [...this.cleanedData] : [...this.mockData]
        const { name, class: className, subject, clusterType } = this.listQuery

        if (name) {
          result = result.filter(item => item.name.includes(name))
        }

        if (className) {
          result = result.filter(item => item.class === className)
        }

        if (subject) {
          result = result.filter(item => item.subject === subject)
        }

        if (clusterType) {
          result = result.filter(item => item.clusterType === clusterType)
        }

        this.total = result.length
        const { page, limit } = this.listQuery
        const start = (page - 1) * limit
        const end = page * limit
        this.list = result.slice(start, end)
        this.listLoading = false
      }, 500)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: undefined,
        clusterType: undefined
      }
      this.isDataCleaned = false
      this.getList()
    },
    exportData() {
      const ws = XLSX.utils.json_to_sheet(this.list)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'cluster_analysis.xlsx')
    },
    handleRowClick(row) {
      this.selectedStudent = { ...row }
      this.dialogVisible = true
    },
    showStudentProfile(row) {
      this.portraitDialogVisible = true
      this.$nextTick(() => {
        this.drawLearningStyleRadar(row)
      })
    },
    drawLearningStyleRadar(row) {
      const learningStyle = row.learningStyle
      const radarChart = echarts.init(document.getElementById('learning-style-radar'))
      const radarOption = {
        title: {
          text: '学习风格雷达图',
          left: 'center'
        },
        radar: {
          indicator: [
            { name: '语言智能', max: 10 },
            { name: '逻辑智能', max: 10 },
            { name: '空间智能', max: 10 },
            { name: '音乐智能', max: 10 },
            { name: '身体运动智能', max: 10 },
            { name: '人际智能', max: 10 },
            { name: '内省智能', max: 10 }
          ]
        },
        series: [
          {
            type: 'radar',
            data: [
              {
                value: [
                  learningStyle.language,
                  learningStyle.logic,
                  learningStyle.spatial,
                  learningStyle.musical,
                  learningStyle.bodily,
                  learningStyle.interpersonal,
                  learningStyle.intrapersonal
                ],
                name: '学习风格'
              }
            ]
          }
        ]
      }
      radarChart.setOption(radarOption)
    },
    showLearningPath(row) {
      this.pathDialogVisible = true
      this.$nextTick(() => {
        this.drawLearningPath(row)
      })
    },
    drawLearningPath(row) {
      const pathChart = echarts.init(document.getElementById('learning-path-chart'))
      const pathOption = {
        title: {
          text: '个性化学习路径',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['基础知识', '核心概念', '应用实践', '综合提升', '创新拓展']
        },
        yAxis: {
          type: 'value',
          name: '掌握程度'
        },
        series: [
          {
            name: '学习进度',
            type: 'line',
            data: this.generateLearningPathData(row),
            markPoint: {
              data: [
                { type: 'max', name: '最高点' },
                { type: 'min', name: '最低点' }
              ]
            }
          }
        ]
      }
      pathChart.setOption(pathOption)
    },
    generateLearningPathData(row) {
      const baseData = {
        优秀进取型: [85, 90, 95, 98, 100],
        稳定发展型: [70, 75, 80, 85, 90],
        潜力待发型: [60, 65, 75, 80, 85],
        困难提升型: [50, 55, 65, 70, 75]
      }
      return baseData[row.clusterType] || [60, 65, 70, 75, 80]
    },
    showRecommendations(row) {
      this.selectedRecommendations = this.generateRecommendations(row)
      this.recommendationDialogVisible = true
    },
    generateRecommendations(row) {
      const recommendations = []

      switch (row.clusterType) {
        case '优秀进取型':
          recommendations.push(
            {
              title: '深化学习',
              content: '建议增加高阶思维训练，参与学科竞赛，培养创新思维。'
            },
            {
              title: '知识拓展',
              content: '可以尝试跨学科学习，建立知识体系，提升综合素养。'
            },
            {
              title: '能力提升',
              content: '建议参与研究性学习，培养独立思考和解决问题的能力。'
            }
          )
          break
        case '稳定发展型':
          recommendations.push(
            {
              title: '巩固基础',
              content: '建议加强基础知识复习，确保知识点的牢固掌握。'
            },
            {
              title: '提升效率',
              content: '可以尝试优化学习方法，提高学习效率。'
            },
            {
              title: '拓展训练',
              content: '建议适当增加练习难度，提升解题能力。'
            }
          )
          break
        case '潜力待发型':
          recommendations.push(
            {
              title: '查漏补缺',
              content: '建议系统梳理知识盲点，及时弥补知识漏洞。'
            },
            {
              title: '方法指导',
              content: '需要加强学习方法指导，培养良好的学习习惯。'
            },
            {
              title: '信心培养',
              content: '建议多给予鼓励，增强学习信心。'
            }
          )
          break
        case '困难提升型':
          recommendations.push(
            {
              title: '基础强化',
              content: '建议从最基础的知识点开始，循序渐进地学习。'
            },
            {
              title: '个性化辅导',
              content: '需要针对性的辅导，解决学习困难。'
            },
            {
              title: '心理支持',
              content: '建议加强心理辅导，建立学习信心。'
            }
          )
          break
      }

      if (row.homeworkAccuracy < 70) {
        recommendations.push({
          title: '作业质量提升',
          content: '建议加强作业完成质量，提高作业准确率。'
        })
      }

      if (row.videoWatchCount < 5) {
        recommendations.push({
          title: '视频学习',
          content: '建议增加视频学习时间，加深对知识点的理解。'
        })
      }

      if (row.interactionCount < 3) {
        recommendations.push({
          title: '互动参与',
          content: '建议积极参与课堂互动，提高学习参与度。'
        })
      }

      return recommendations
    },
    cleanData() {
      this.listLoading = true
      setTimeout(() => {
        // 清洗数据
        this.cleanedData = this.mockData.filter(item => {
          // 检查关键字段是否存在且有效
          const hasValidScore = item.examScore !== null && !isNaN(item.examScore) && item.examScore >= 0 && item.examScore <= 100
          const hasValidClusterType = item.clusterType && ['优秀进取型', '稳定发展型', '潜力待发型', '困难提升型'].includes(item.clusterType)
          const hasValidHomeworkAccuracy = item.homeworkAccuracy !== null && !isNaN(item.homeworkAccuracy) && item.homeworkAccuracy >= 0 && item.homeworkAccuracy <= 100
          const hasValidVideoWatchCount = item.videoWatchCount !== null && !isNaN(item.videoWatchCount) && item.videoWatchCount >= 0
          const hasValidInteractionCount = item.interactionCount !== null && !isNaN(item.interactionCount) && item.interactionCount >= 0
          const hasValidWeeklyHours = typeof item.weeklyStudyHours === 'number' && !isNaN(item.weeklyStudyHours) && item.weeklyStudyHours >= 30 && item.weeklyStudyHours <= 60

          // 所有条件都必须满足
          const isValid = hasValidScore && hasValidClusterType && hasValidHomeworkAccuracy &&
                         hasValidVideoWatchCount && hasValidInteractionCount && hasValidWeeklyHours

          return isValid
        })

        this.isDataCleaned = true
        this.$message({
          message: `数据清洗完成，共清除 ${this.mockData.length - this.cleanedData.length} 条异常数据，剩余 ${this.cleanedData.length} 条有效数据`,
          type: 'success'
        })

        // 重新获取列表数据
        this.getList()
        this.listLoading = false
      }, 2500)
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;

  .el-form-item {
    margin-bottom: 10px;
  }
}

.recommendation-container {
  .recommendation-card {
    margin-bottom: 20px;
  }

  .recommendation-item {
    margin-bottom: 15px;

    h4 {
      margin: 0 0 10px 0;
      color: #409EFF;
    }

    p {
      margin: 0;
      color: #606266;
    }
  }
}
</style>
